package com.geostart.constructionland.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.geostart.constructionland.system.service.JspContentService;
import org.springframework.stereotype.Service;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.geostart.constructionland.system.dto.JspContentDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * <接口或类描述>
 *
 * @author chenjianjun
 * @since 2021-01-21 19:11
 */
@Service
@Slf4j
public class JspContentServiceImpl implements JspContentService {

    @Override
    public Map<String, String> getJspContent(List<JspContentDTO> jspContentDTOList) {
        Map<String, String> result = new HashMap<>();
        // 新建一个模拟谷歌internet浏览器的浏览器客户端对象
        try (WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER)) {
            // 当JS执行出错的时候是否抛出异常, 这里选择不需要
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            // 当HTTP的状态非200时是否抛出异常, 这里选择不需要
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setActiveXNative(false);
            // 是否启用CSS, 因为不需要展现页面, 所以不需要启用
            webClient.getOptions().setCssEnabled(false);
            // 很重要，启用JS
            webClient.getOptions().setJavaScriptEnabled(true);
            // 很重要，设置支持AJAX
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            for (JspContentDTO jspContent : jspContentDTOList) {
                HtmlPage page = webClient.getPage(jspContent.getUrl());
                // 异步JS执行需要耗时,所以这里设置时间,等待异步JS执行结束
                webClient.waitForBackgroundJavaScript(jspContent.getTimeoutMillis());
                // 直接将加载完成的页面转换成xml格式的字符串
                result.put(jspContent.getHtmlType(), page.asXml());
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
